package me.leiusual.sharing.ui.product.adapter

import android.view.LayoutInflater
import android.view.View
import androidx.core.content.res.ResourcesCompat
import androidx.recyclerview.widget.RecyclerView
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import com.zhy.view.flowlayout.TagFlowLayout
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.view_holder_product_optional.*
import kotlinx.android.synthetic.main.view_holder_product_optional_tag.view.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.ProductDetail
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class ProductOptionalViewHolder(
    override val containerView: View,
    private val listener: Listener
) : RecyclerView.ViewHolder(containerView), LayoutContainer, TagFlowLayout.OnTagClickListener {

  private lateinit var option: ProductDetail.Option

  private val optionValues = mutableListOf<ProductDetail.Option.OptionValue>()

  init {
    tag_flow_layout.setOnTagClickListener(this)
    tag_flow_layout.adapter = object : TagAdapter<ProductDetail.Option.OptionValue>(optionValues) {
      override fun getView(parent: FlowLayout, position: Int, t: ProductDetail.Option.OptionValue): View {
        val inflater = LayoutInflater.from(parent.context)
        val tagView = inflater.inflate(R.layout.view_holder_product_optional_tag, parent, false)
        tagView.text_view_tag_name.text = t.value
        if (!t.enabled) {
          tagView.text_view_tag_name.setBackgroundResource(R.drawable.product_optional_tag_disable_selector)
          val color = ResourcesCompat.getColor(parent.resources, R.color.text_color_gray_light, null)
          tagView.text_view_tag_name.setTextColor(color)
        }
        return tagView
      }
    }
  }

  @Suppress("DEPRECATION")
  fun bind(option: ProductDetail.Option) {
    this.option = option

    // 名称
    text_view_name.text = option.name

    // 可选值
    optionValues.clear()
    optionValues.addAll(option.productOptionValues)

    // 默认
    val indexOfFirst = option.productOptionValues.indexOfFirst { it.checked }
    tag_flow_layout.adapter.setSelectedList(if (indexOfFirst >= 0) setOf(indexOfFirst) else emptySet())
    tag_flow_layout.adapter.notifyDataChanged()
  }

  override fun onTagClick(view: View, position: Int, parent: FlowLayout): Boolean {
    Timber.v("position = %s", position)

    // 清除旧的
    option.productOptionValues.forEach {
      it.checked = false
    }

    // 选中新的
    val index = tag_flow_layout.selectedList.firstOrNull()
    if (index != null) {
      val optionValue = option.productOptionValues[index]
      if (optionValue.enabled) {
        optionValue.checked = true
      }
    }
    listener.onTagClicked()
    return true
  }

  interface Listener {

    fun onTagClicked()
  }
}